package com.dhj.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dhj.yygh.model.hosp.Department;
import com.dhj.yygh.mongo_operation.DepartmentTemplate;
import com.dhj.yygh.service.DepartmentService;
import com.dhj.yygh.vo.hosp.DepartmentQueryVo;
import com.dhj.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentTemplate departmentTemplate;

    @Autowired
    private MongoRepository<Department, String> departmenRepository;

    /**
     * 保存在科室信息
     * @param stringObjectMap 传递过来的参数集合 参数集合
     */
    @Override
    public void saveDepartment(Map<String, Object> stringObjectMap) {

        String str = JSONObject.toJSONString(stringObjectMap);

        Department department = JSONObject.parseObject(str, Department.class);

        Department departmentByDepcode =
                departmentTemplate.getDepartmentByDepcodeAndHoscode(
                        department.getDepcode(), department.getHoscode());

        // 若科室存在，则更新信息，做修改操作
        if (departmentByDepcode != null) {
            department.setId(departmentByDepcode.getId());
            department.setUpdateTime(new Date());
            department.setIsDeleted(departmentByDepcode.getIsDeleted());
            departmenRepository.save(department);
            return;
        }

        department.setCreateTime(new Date());
        department.setIsDeleted(0);
        department.setUpdateTime(new Date());
        // 使用 Repository 来区分执行保存和修改操作
        departmenRepository.save(department);
    }

    /**
     * 查询科室的分页信息
     *
     * @param page              当前页
     * @param limit             每页记录数
     * @param departmentQueryVo 查询的条件的 vo 对象
     * @return 返回分页对象
     */
    @Override
    public Page<Department> getDeparmentPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);

        // 构造模糊查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                // 通过字符串来匹配,匹配模式为 tringMatcher.CONTAINING: 包含
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true); // 忽略大小写

        // 构造条件
        Example<Department> example = Example.of(department, matcher);

        // 构造 Pageable 对象
        Pageable pageable = PageRequest.of(page, limit);

        Page<Department> departmentPage = departmenRepository.findAll(example, pageable);
        return departmentPage;
    }


    /**
     * 按照科室编号和医院编号查询科室信息，根据id删除科室信息
     *
     * @param hoscode 医院编号
     * @param depcode 科室编号
     */
    @Override
    public Long removeDepartmentByDepcodeAndHoscode(String hoscode, String depcode) {
        return departmentTemplate.removeDepartmentByDepcodeAndHoscode(hoscode, depcode);
    }

    /**
     * 根据医院编号查询科室信息
     *
     * @param id
     * @return
     */
    @Override
    public List<DepartmentVo> getDepartmentInfoByHoscode(String hoscode) {

        // 用于最后的结果封装
        List<DepartmentVo> result = new ArrayList<>();

        // 根据医院编号查询所有的科室信息
        List<Department> departmentList =
                departmentTemplate.getDepartmentListByHoscode(hoscode);

        /*
         根据大科室代码 bigcode 分组
         */

        // stream 流的写法(按照 bigcode 分组)
        Map<String, List<Department>> departmentGroupMap = departmentList.stream().collect(Collectors.groupingBy(
                Department::getBigcode
        ));

        // 遍历 Map
        Set<Map.Entry<String, List<Department>>> entries = departmentGroupMap.entrySet();
        for (Map.Entry<String, List<Department>> entry : entries) {
            // 大科室编号
            String bigcode = entry.getKey();

            // 大科室对应的所有子科室集合
            List<Department> departmentValueList = entry.getValue();

            /*
             封装科室数据到 DepartmentVo
             */

            DepartmentVo departmentVo = new DepartmentVo();

            // 设置大科室的编号
            departmentVo.setDepcode(bigcode);
            // 设置大科室的名称，因为对应的科室数据都属于同一个大科室，因此直接取出一个子科室，获取其 bigname 科室名称即可
            departmentVo.setDepname(departmentValueList.get(0).getBigname());

            /*
             设置大科室的所有子科室
             */
            // 遍历子科室的 Department 集合,封装到子科室的 DepartmentVo 集合中
            List<DepartmentVo> departmentVos = new ArrayList<>();
            for (Department department : departmentValueList) {
                DepartmentVo departmentVo1 = new DepartmentVo();

                // 设置子科室集合中每个科室的科室编号 depcode
                departmentVo1.setDepcode(department.getDepcode());
                // 设置子科室集合中每个科室的科室名称 depname
                departmentVo1.setDepname(department.getDepname());
                // 放入子科室集合
                departmentVos.add(departmentVo1);
            }
            // 设置子科室集合到 大科室的 departmentVo 中
            departmentVo.setChildren(departmentVos);

            // 添加大科室 departmentVo 对象到最终返回结果的 result 集合
            result.add(departmentVo);
        }
        return result;
    }
}
